﻿using System;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;
using WorldMapBase;
using WorldMapBase.Tile.Pool;
using WorldMapNew;
using XLua;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using DG.Tweening;
using System.Timers;
using com.yoozoo.gta.Extension;
using Yoozoo.Mars.Got;
using LogSystem;
using Yoozoo.Gta.Common;

/// <summary>
/// 地图势力范围
/// </summary>
public class MapWonderArea
{
    private ResLoader m_resLoader;
    private GameObject worldAreaRoot; // 奇观区域根节点 
    private bool bAreaShow = false;

    private Dictionary<int, Color> areaColors = new Dictionary<int, Color>();
    private Dictionary<int, int> areaColorRecords = new Dictionary<int, int>();

    private Dictionary<int, GameObject> wonderAreaObjs = new Dictionary<int, GameObject>();
    private Dictionary<int, Material> wonderAreaMats = new Dictionary<int, Material>();

    private bool isDebug = false;//GameHelper.IsDevelopmentBuild();
    
    public void InitArea()
    {
        if (worldAreaRoot == null) worldAreaRoot = new GameObject("[CSWorldAreaObjRoot]");
        worldAreaRoot.transform.position = new Vector3(WorldEntry.m_mapLandSize * 0.5f, 0, WorldEntry.m_mapLandSize * 0.5f);
        worldAreaRoot.transform.rotation = Quaternion.Euler(0, 180, 0);
        worldAreaRoot.SetActive(false);
        bAreaShow = false;
    }
    string mapAreaPrefabPath = "Assets/ResourcesAssets/World/prefabs/sandtable/floor/floor_{0}.prefab";
    public void LoadArea(int wonderId, LuaFunction callBack)
    {
        if (wonderAreaObjs != null && wonderAreaObjs.TryGetValue(wonderId, out GameObject obj))
        {
            callBack?. Action();
            obj.SetActive(true);
            return;
        }

        // 实例化势力obj
        string path = string.Format(mapAreaPrefabPath, wonderId);
        if (m_resLoader == null)
        {
            m_resLoader = ResLoader.Alloc();
        }
        m_resLoader.Add2Load(path, (bool success, string assetName, object asset) =>
        {
            if (success)
            {
                // 捕获对应节点
                GameObject obj = GameObject.Instantiate<GameObject>(asset as GameObject);
                obj.transform.SetParent(worldAreaRoot.transform,false);
                obj.transform.localPosition = Vector3.zero;
                obj.name = "WonderArea_" + wonderId;
                obj.SetActive(false);
                Material mat = obj.GetComponent<MeshRenderer>().material;
                wonderAreaObjs[wonderId] = obj;
                wonderAreaMats[wonderId] = mat;
                callBack?. Action();
                //4.30新增，异步加载回来检查一下数据是否需要设置
                if (areaColorRecords.TryGetValue(wonderId, out int colorId) && colorId > 0)
                {
                    UpdateAreaColor(wonderId,colorId);
                }
            }
        });
        m_resLoader.Load();
    }

    public void InitAraeColor(int colorId,string str_c)
    {
        if (!String.IsNullOrEmpty(str_c) && ColorUtility.TryParseHtmlString(str_c, out Color color))
        {
            color.a = 0.4f;
            areaColors[colorId] = color;
        }
    }

     //检查一下是否有数据，第二次加载的时候有可能数据在颜色初始化之前就设置好了
    public void SetAllAreaColor()
    {
        foreach (var item in areaColorRecords)
        {
            UpdateAreaColor(item.Key,item.Value,false);
        }
    }

    public void UpdateAreaColor(int wonderId, int colorId,bool addToMap = true)
    {
        if (addToMap)
        {
            areaColorRecords[wonderId] = colorId;
        }
        Color c = Color.black;
        //如果颜色还没设置，则先存下数据，等颜色设置好了再赋值
        if (areaColors.ContainsKey(colorId))
        {
            c = areaColors[colorId];
        }
        else
        {
            if (isDebug)
            {
                UnityEngine.Debug.LogError(string.Format("wonderId = {0},colorId = {1},不存在该颜色，直接退出", wonderId, colorId));
            }
            return;// 不存在该颜色 直接退出不显示
        }
        // 检查记录
        /*if (areaColorRecords.ContainsKey(wonderId))
        {
            if (areaColorRecords[wonderId] == colorId)
            {
                UnityEngine.Debug.LogError(string.Format("wonderId = {0},colorId = {1},已经染过色了", wonderId, colorId));
                return;
            }
        }*/
        if (wonderAreaMats.TryGetValue(wonderId, out Material mat))
        {
            if (colorId > 0)
            {
                mat.SetColor("_Color", c);
            }

            if (isDebug)
            {
                UnityEngine.Debug.LogError(string.Format("wonderId = {0},colorId = {1},染色成功", wonderId, colorId));
            }
            wonderAreaObjs[wonderId].SetActive(colorId > 0);
        }
        else
        {
            if (isDebug)
            {
                UnityEngine.Debug.LogError(string.Format("wonderId = {0},colorId = {1},染色失败，因为材质没有回来", wonderId, colorId));
            }
        }
    }

    //public void UpdateMask()
    //{
    //    if (areaMask)
    //    {
    //        areaMask.Apply();
    //    }
    //}

    public void UpdateWonderAreaShow(bool bShow)
    {
        if (worldAreaRoot) worldAreaRoot.gameObject.SetActive(bShow);
    }

    public void Destroy()
    {
        if (m_resLoader != null)
        {
            m_resLoader.Recycle2Cache();
            m_resLoader = null;
        }
        if (worldAreaRoot)
        {
            GameObject.Destroy(worldAreaRoot);
            worldAreaRoot = null;
        }
        //areaMat = null;
        bAreaShow = false;
        areaColors.Clear();
        areaColorRecords.Clear();
    }

    public void SwitchServer()
    {
        if (wonderAreaObjs != null)
        {
            foreach (var obj in wonderAreaObjs.Values)
            {
                if (obj != null && obj.Valid())
                {
                    obj.SetActive(false);
                }
            }
        }
    }
}